package src.sort;

/**
 * @author starsea
 * @date 2024-06-24 13:02
 */

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 时间复杂度：O(N*log^N)
 * 空间复杂度：O(1)
 * 稳定性：不稳定
 */
public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {27, 15, 19, 18, 28, 34, 65, 49, 25, 37};
        //常用接口
        PriorityQueue<Integer> priorityQueue=new PriorityQueue<>();
        PriorityBlockingQueue<Integer> priorityBlockingQueue=new PriorityBlockingQueue<>();

        deleteElemt(createHeap(arr,80));


    }

    public static int[]  createHeap(int[] arr,int elemt) {
        int len = arr.length;
        //扩容
        arr=Arrays.copyOf(arr,arr.length+1);

        arr[arr.length-1]=elemt;
        for (int i = len-1; i >= 0; i--) {
            int parent = (i - 1) / 2;
            //siftDwon(arr, parent);
            siftUp(arr,i,len);
           // System.out.println("向下调整的每一步："+Arrays.toString(arr));
            //System.out.println("向上调整的每一步："+Arrays.toString(arr));
        }
        return arr;
    }
//向下调整
    public static void siftDwon(int[] arr, int parent) {
        int child = parent * 2 + 1;
        while (child < arr.length) {
            if (child + 1 < arr.length && arr[child + 1] > arr[child]) {
                child++;
            }
            if (arr[parent] < arr[child]) {
                swap(arr, parent, child);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }
    //向上调整
    public static void  siftUp(int[] arr,int child,int usedSize)
    {
        int parent=(child-1)/2;
        while (child>0)
        {
            if(child+1<usedSize && arr[child+1]>arr[child])
            {
                child++;
            }
            if(arr[child]>=arr[parent])
            {
                swap(arr,child,parent);
                child=parent;
                parent=(child-1)/2;
            }
            else
            {
                break;
            }
        }
    }
    //删除堆头元素：1.交换堆头堆尾元素，2.usedsize减一3.再次调整
    public static void deleteElemt(int[] arr)
    {
        int len=arr.length;
        swap(arr,0,len-1);
        for (int i = len-2; i >= 0; i--) {
            int parent = (i - 1) / 2;
            //siftDwon(arr, parent);
            siftUp(arr,i,len-2);
            // System.out.println("向下调整的每一步："+Arrays.toString(arr));
            System.out.println("删除调整的每一步："+Arrays.toString(arr));
        }
    }


    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}
